/**
 * server module
 */

import express from 'express';
import bodyParser from 'body-parser';
import multer from 'multer';
import logger from 'morgan';
import {createServer} from 'http';
import jade from 'jade';
import path from 'path';
import favicon from 'serve-favicon';
import socketIo from 'socket.io';
import session from 'express-session';
import errorhandler from 'errorhandler';
import notifier from 'node-notifier';
import cookieParser from 'cookie-parser';
import routes from './routes';


let app = express();
let upload = multer({dest: 'uploads/'});
// all environments
app.set('env', _U.config.evn);
app.set('port', _U.config.port);
// set views
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// set cookie
app.use(cookieParser('secret'));

app.use(favicon(__dirname + '/public/favicon.ico'));

app.use(bodyParser.json()); // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })); // for parsing application/x-www-form-urlencoded

//  数据库连连接池 (默认为mongodb)

_U.db().connection({debug: _U.config.evn === 'dev' ? true : false});


let sess = {
  secret: 'xiaoqi',
  genid: function(req) {
  //  return genuuid() // use UUIDs for session IDs
  },
  cookie: {maxAge: 1 * 60 * 60 * 1000 }
};

if (app.get('env') === 'dev') {
  // only use in development
	app.use(errorhandler({log: (err, str, req) => {
		  	var title = `Error in ${req.method}  ${req.url}`
			notifier.notify({
				title: title,
				message: str
			});
		}}
	));
}else{
  app.set('trust proxy', 1) // trust first proxy
  sess.cookie.secure = true // serve secure cookies
}

// set session
app.use(session(sess));

// routes
app.use(routes);

 //connect 内建的中间件 在终端显示简单的日志。
app.use(logger('dev'));
/**
app.use(function(req, res) {
  res.send('asdas');
});
**/
// 创建HTTP服务
const server = createServer(app);
// websocket服务创建
const io = socketIo.listen(server);

server.listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
  if (app.get('env') === 'd1ev') require('open')(_U.config.url);
  
});
